<template>
  <div>
    <div>
      <div class=" album-up-add">
        <i class="el-icon-plus"></i>
        <span>选择图片</span>
        <input type="file" class="album-up-file" multiple @change="upFiles($event)" />
      </div>
      <el-button class="com-btn" icon="el-icon-check" size="small" @click="save()">保存至相册</el-button>
    </div>
    <div>
      <el-row :gutter="20">
        <el-col :span="6" v-for="(item,index) in up_list" :key="index">
          <div class="img-up-item">
            <el-image
              :src="$oss_url + item.src + '?x-oss-process=image/resize,h_300'"
              fit="cover"
              class="img-up-image"
              v-if="item.src"
            ></el-image>
            <div v-else style="text-align:center">
              <el-progress type="circle" :percentage="item.process"></el-progress>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
export default {
  props:{album_id : {}},
  data() {
    return {
      up_list: []
    };
  },
  mounted(){
  },
  methods: {
    //保存
    save(){
      var list = [];
      var item = {};
      for(var i in this.up_list) {
        item = {
          src : this.up_list[i].src,
          album_id : this.album_id
        };
        list.push(item);
      }
      this.ajaxs('album/savePhoto',{
        data : {list : list},
        success:(res) =>{
          this.toast(res.code,res.msg);
          if(res.code) {
            this.$emit('change');
          }
          console.log(res);
        }
      });
    },
    //上传
    upFiles(e) {
      var file = e.currentTarget.files;
      var len = file.length;
      var total_len = this.up_list.length;
      for (var i = total_len; i < len + total_len; i++) {
        var item = {
          process: 0,
          src: ""
        };
        this.up_list.push(item);
        this.fileUpload(file[i - total_len], i);
      }
    },
    fileUpload(img, index) {
      if (img == undefined) return false;
      //获取文件后缀名
      var arr = img["name"].split(".");
      var img_type = arr[1];
      let OSS = require("ali-oss");
      let client = new OSS({
        region: "oss-cn-hangzhou",
        //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
        accessKeyId: "LTAIWdxCuPiIzLfm",
        accessKeySecret: "z1zLih5CgWNkWfuzHj7SbpJKVdME2a",
        bucket: "ykp-new"
      });
      // client.options.endpoint.protocol = "https:";
      //获取当前时间
      var date = new Date();
      var file_name =
        date.getFullYear() +
        "/" +
        (date.getMonth() + 1) +
        "/" +
        date.getDate() +
        "/" +
        date.getHours() +
        "_" +
        date.getMinutes() +
        "_" +
        date.getSeconds() +
        "_" +
        date.getMilliseconds();
      let filename = "/active/cover/" + file_name + "." + img_type;
      let res_file = img;
      let that = this;
      async function put() {
        try {
          //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
          let result = await client
            .multipartUpload(filename, res_file, {
              progress: percentage => {
                that.up_list[index].process = parseInt(percentage * 100);
                //console.log(percentage); // 上传文件进度
              }
            })
            .then(res => {
              that.up_list[index].src = res.name;
            })
            .catch(err => {
              return that.toast(0, "上传失败");
            });
        } catch (e) {
          return that.toast(0, "上传失败");
        }
      }
      put();
    }
  }
};
</script>

<style>
.img-up-image {
  width: 100%;
  height: 100%;
}
.img-up-item {
  width: 100%;
  height: 160px;
  margin-top: 20px;
}
.album-up-file {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  opacity: 0;
  cursor: pointer;
}
.album-up-add {
  width: 140px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  border-radius: 3px;
  cursor: pointer;
  position: relative;
  float: left;
  margin-right: 10px;
  background: #E6A23C;
  color: #fff;
}
.album-up-add i {
  margin-right: 5px;
}
</style>